package kokonut.shop.cart;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BuyServlet extends HttpServlet{
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws IOException {

		Cart cart = Cart.getInstance();
		resp.setContentType("text/plain");
        resp.getWriter().println("Compra realizada. Gasto Total: "+cart.getTotal());
		sendEmail();
	}

	private void sendEmail()
	{
		Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        String msgBody = "Hello this is a new BUY order";

        try {
            Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress("kokonut@kokonut.com", "Kokonut.com Admin"));
            msg.addRecipient(Message.RecipientType.TO,
                             new InternetAddress("markel.arizaga@gmail.com", "Markel"));
            msg.setSubject("New BUY ORDER");
            msg.setText(msgBody);
            Transport.send(msg);

        } catch (UnsupportedEncodingException e){
			e.printStackTrace();
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
        	e.printStackTrace();
        }
	}

}